package com.atom.common.remote.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;
import java.util.UUID;

import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.atom.common.CommonConstant;
import com.atom.common.exception.AvensFileException;
import com.atom.common.util.GlobalConfigReader;

/**
 * Title: RemoteFileCommand
 * Description: 用命令行上传文件，已改成用JAR包上传文件
 * @author WEWE
 * @date 2016年10月21日 下午4:15:50
 * @version 1.0
 */
@Component
public class RemoteFileCommand {

  Logger logger = Logger.getLogger(RemoteFileCommand.class);

  private static final String DATAMANAGE_HOME = GlobalConfigReader.getStringValue(CommonConstant.DATAMANAGE_HOME);
  private static final String FTL_DOWNLOAD = GlobalConfigReader.getStringValue(CommonConstant.FTL_DOWNLOAD);
  private static final String BUCKET_NAME = GlobalConfigReader.getStringValue(CommonConstant.BUCKET_NAME);
  private static final String APP_ID = GlobalConfigReader.getStringValue(CommonConstant.APP_ID);
  private static final String APPEND_URL = GlobalConfigReader.getStringValue(CommonConstant.APPEND_URL);
  private static final String FILE_MD5ASHEX_URL = GlobalConfigReader.getStringValue(CommonConstant.FILE_MD5ASHEX_URL);
  private static final String LOGGER_URL = GlobalConfigReader.getStringValue(CommonConstant.LOGGER_URL);
  private static final String DB_POOL_NAME = GlobalConfigReader.getStringValue(CommonConstant.DB_POOL_NAME);
  private static final String DB_POOL_PATH = RemoteFileCommand.class.getClassLoader().getResource("").getPath();
  //private static final String DB_POOL_PATH = GlobalConfigReader.getStringValue(CommonConstant.DB_POOL_PATH);
//  private static final ClientConfig CONFIG = new ClientConfig(APP_ID, APPEND_URL, FILE_MD5ASHEX_URL,
//      LOGGER_URL, DB_POOL_NAME, DB_POOL_PATH);


  public String uploadFileByJar(String filePath) {
//    logger.info("=====upload begin=====");
//    logger.info("FILEPATH : " + filePath);
//    GugongS3 S3 = new GugongS3Client(CONFIG);
//    File file = new File(filePath);
//    String uploadFilePath = file.getPath();
//    String fileName = file.getName();    
//    File uploadFile = new File(uploadFilePath);    
    String uuid = UUID.randomUUID().toString();
//    GPutObjectRequest uploadRequest = new GPutObjectRequest(BUCKET_NAME, uuid,
//        uploadFile);
//    GObjectMetadata metadata = new GObjectMetadata();
//    Map<String, String> userMetadata = new HashMap<String, String>();
//    userMetadata.put("FileName", fileName);
//    metadata.setUserMetadata(userMetadata);
//    uploadRequest.setMetadata(metadata);
//    GPutObjectResult result = S3.putObject(uploadRequest);
//    S3.close();
//    logger.info(JsonUtil.ObjectToJsonQuietly(result));
//    logger.info("=====upload finish=====");
    return uuid;
  }
  

  public String downloadFileByJar(String key) {
    /*logger.info("=====download begin=====");
    logger.info("KEY : " + key);
    // 获取文件名称
    GugongS3 S3 = new GugongS3Client(CONFIG);
    String fileName = getFileName(S3, key);
    if (fileName == null || fileName.isEmpty()) {
      throw new AvensFileException("Download html failed that fileName is null!");
    }
    logger.info("FILENAME : " + fileName);
    // 下载文件
    GGetObjectRequest downloadRequest = new GGetObjectRequest(BUCKET_NAME,
        key);
    GS3Object result = S3.getObject(downloadRequest);
    GS3ObjectInputStream in = result.getObjectContent();
    String filePath = FTL_DOWNLOAD;
    File downfile = new File(filePath + File.separator + fileName);
    try {
      // 创建输出流
      OutputStream out = new FileOutputStream(downfile);
      // 创建缓冲区
      byte buffer[] = new byte[1024];
      int len = 0;
      // 循环将输入流中的内容读取到缓冲区当中
      while ((len = in.read(buffer)) > 0) {
        // 输出缓冲区的内容到浏览器，实现文件下载
        out.write(buffer, 0, len);
      }
      // 关闭文件输入流
      in.close();
      // 关闭输出流
      out.close();
      // 关闭S3
      S3.close();
    } catch (Exception e) {      
      e.printStackTrace();
    }
    logger.info("=====download finish=====");
    return downfile.getPath();*/
	  return "";
  }
  
//  private String getFileName(GugongS3 S3, String key) {
//    /*String fileName = null;
//    GGetObjectMetadataRequest metadataRequest = new GGetObjectMetadataRequest(BUCKET_NAME,
//        key);
//    GObjectMetadata objectMetadata = S3.getObjectMetadata(metadataRequest);
//    if (objectMetadata != null) {
//      Map<String, String> userMetadata = objectMetadata.getUserMetadata();
//      if (userMetadata != null && userMetadata.containsKey("FileName")) {
//        fileName = userMetadata.get("FileName");
//      }
//    }
//    return fileName;*/
//	  return "";
//  }
  
  @Deprecated
  public String uploadFile(String filePath) {
    File file = new File(filePath);
    if(file.exists()) {
      logger.info("file exists : " + filePath);
    } else {
      logger.info("file not found : " + filePath);
    }
    String java = DATAMANAGE_HOME + File.separator 
        + "Java" + File.separator 
        + "jdk1.8.0_101" + File.separator 
        + "bin" + File.separator 
        + "java";
    String datamanagejar = DATAMANAGE_HOME + File.separator 
        + "datamanageclient.jar";
    if(filePath.contains(" ")) {
      filePath = "\""+filePath + "\"";
    }
    RemoteFileCommand demo = new RemoteFileCommand();
    String cmdLine = java + " -jar " + datamanagejar+ " upload " + filePath;
    logger.info("=====upload begin=====");
    logger.info("CMDLine : " + cmdLine);
    String result = demo.executeCommand(DATAMANAGE_HOME, cmdLine);
    logger.info("Result : " + result);
    logger.info("=====upload finish=====");
    JSONObject jsonResult = new JSONObject(result);
    if (StringUtils.equals("true", jsonResult.getString("status"))) {
      return jsonResult.getString("object_key");
    }
    return null;
  }
  
  @Deprecated
  public String downloadFile(String key) {
    String java = DATAMANAGE_HOME + File.separator 
        + "Java" + File.separator 
        + "jdk1.8.0_101" + File.separator 
        + "bin" + File.separator 
        + "java";
    String datamanagejar = DATAMANAGE_HOME + File.separator 
        + "datamanageclient.jar";
    String filePath = FTL_DOWNLOAD;
    RemoteFileCommand demo = new RemoteFileCommand();
    String cmdLine = java + " -jar " + datamanagejar+ " download " + key + " " + filePath;
    logger.info("=====download begin=====");
    logger.info("CMDLine : " + cmdLine);
    String result = demo.executeCommand(DATAMANAGE_HOME, cmdLine);
    logger.info("Result : " + result);
    logger.info("=====download finish=====");
    JSONObject jsonResult = new JSONObject(result);
    if (StringUtils.equals("true", jsonResult.getString("status"))) {
      return jsonResult.getString("filepath");
    } else {
      logger.error(result);
    }
    return null;
  }

  /**
   * Description: 在后台执行命令行
   * @param home
   * @param cmdLine 命令行
   * @return 在后台执行命令行成功返回ture，否则返回false
   */
  private String executeCommand(String home, String cmdLine) {
    StringBuffer retValue = new StringBuffer();

    try {
      Process process = Runtime.getRuntime().exec(cmdLine, null, new File(home));
      if (0 == process.waitFor()) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();
        retValue.append(line);
        while (line != null) {
          line = reader.readLine();
          if(line != null) {
            retValue.append(line);
          }
        }
        reader.close();
      } else {
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line = reader.readLine();
        retValue.append(line);
        while (line != null) {
          line = reader.readLine();
          if(line != null) {
            retValue.append(line);
          }
        }
        reader.close();
      }
    } catch (IOException e) {
      String msg = "execute command failed, command: " + cmdLine;
      retValue.append(msg);
    } catch (InterruptedException e) {
      String msg = "wait for command execute fininsh failed, command: " + cmdLine;
      retValue.append(msg);
    }
    String result = retValue.toString();
    int begin = result.indexOf("{");
    int end = result.lastIndexOf("}");
    return result.substring(begin, end + 1);
  }
}
